<?php

/*
 *服务层
 */
namespace app\comm\service;
use app\comm\model\User;
use app\comm\model\UserAddress;
use app\comm\model\UserUserinfo;
use app\comm\model\UserWallet;
use app\comm\model\UserWalletLog;
use app\comm\model\UserYcard;
use app\comm\model\Coupon;
use app\comm\model\UserPointlog;
use app\comm\model\UserCollect;

use ServS\DbShowcollo;
use think\Db;
use app\comm\service\SysToolsLevePoint;
use app\comm\service\AdminUserService;
use app\comm\service\GoodsService;

use \think\Cache;
/**
 * 用户类服务层
 */
class UserService{
/*******************************************************************/	
	/**
	 * 用户注册
	 */
	public function regist($post){
		//dd($post);die;
		$resx = $this->getuserbymobile($post['mobile']);
		if($resx) return 'q';
		$user = new User;
		$user->data([
		    'mobile'     =>  $post['mobile'],
		    'password' 	 =>  MD5($post['password']),
		    'openid'     =>  session('openid'),
		    'mobile'     =>  $post['mobile'],
		    'addtime' 	 =>  time(),
		    'pay_code' 	 =>  rand(1000,9999).time()
		]);
		if($user->save()){
			if(session('uidbyforothercord')){
				$othieruid = session('uidbyforothercord');
				$this -> addbuserpoint($othieruid);
			}
			$post['uid']= $user->uid;
			$post['openid']= session('openid');
			session('_user_uid_',$post);
			return $user->uid;
		}
		return 'w';
	}
	
	/**
	 * 用户查询
	 */
	public function getuserbymobile($mobile){
		$user = User::get(['mobile' => $mobile]);
		return $user ;
	}

	/**
	 * 用户的信息查询
	 */
	public function getuserinfobyuid($uid){
		$userinfo = User::get(['uid' => $uid]);
		if(!$userinfo){
			return  null;
		}
		return $userinfo->toArray() ;
	}

	/**
	 * 用户信息修改
	 * return 1 2 3 ;
	 */
	public function saveuserinfo($post){
		$data = $post;

		//dd($data);die;
		//
		$user = User::where('uid', session('_user_uid_')['uid'])->update($data);
		if($user ){
			return 1;
		}
		return 0;	
	}

	/**
	 * 修改密码
	 * return 1 2 3 
	 */
	public function savepass($post){
		
		$user = User::get(['uid' =>session('_user_uid_')['uid'] ]);
		if($user->password ==md5($post['ordpassword'])){
			if($post['newpass1'] == $post['newpass']){
				User::where('uid', $user->uid)->update([ 'password'=>MD5($post['newpass1'])]);
				return 1;
			}
			return 2;
		}
		return 3;
	}
/*********************************************我的积分*************************************/
	/**
	 * 被邀请的加积分
	 */
	public function addbuserpoint($uid){
		$sytools = new SysToolsLevePoint;
		$adser = new AdminUserService;
		//最后选择那个是要请积分
		$list = $sytools->getpointbyid(5);
		$use = User::where('uid', $uid)->setInc('pay_points', $list['point']);
		$ingo = $adser->getuser($uid);
	 	$data=['uid'=>$uid,'store_id'=>'','uidtype'=>3,'type'=>1,'signid' =>$list['id'],
	 			'point'=>$list['point'], 'curpoint'=>$ingo['pay_points'],'type_cn'=>$list['remark'],'whname'=>$list['remark']];
	 	$userpoint = new UserPointlog;
	 	$res = DbShowcollo::add($userpoint,$data);
	 	return $res;
	}

	/**	
	 * 购物，分享加积分
	 * uid
	 * 积分id
	 * 门店id
	 */
	public function adduserpoint($uid,$pointid,$store_id){
		$sytools = new SysToolsLevePoint;
		$adser = new AdminUserService;
		//最后选择那个是要请积分
		$list = $sytools->getpointbyid($pointid);
		$use = User::where('uid', $uid)->setInc('pay_points', $list['point']);
		$ingo = $adser->getuser($uid);
	 	$data=['uid'=>$uid,'store_id'=>$store_id,'uidtype'=>1,'type'=>1,'signid' =>$list['id'],
	 			'point'=>$list['point'], 'curpoint'=>$ingo['pay_points'],'type_cn'=>$list['remark'],'whname'=>$list['remark']];
	 	$userpoint = new UserPointlog;
	 	$res = DbShowcollo::add($userpoint,$data);
	 	return $res;
	}


	/**
	 * 积分增减日志
	 */
	public function  mypointlist($uid,$type=1,$page=0,$limt=10){
		$userpoint =  UserPointlog::where("uid",$uid)->page($page,$limt) ->order('addtime desc')->select();
		return $userpoint;
	}

	/**
	 * 门店排行
	 */
	public function stordesc($uid,$type=2,$page=0,$limt=10){
		if($type==2){
		//分门店，查询在每个分店的总积分排行
			$userpoint =  UserPointlog::where("uid",$uid)
					 	 ->field('id,sum(point) as count , store_id,addtime , curpoint,type_cn ')
						  ->where("type",1)
						 ->page($page,$limt)
						 ->group('store_id')->order('addtime desc')->select();
		}
		if($type==3){
			//不知道的，看情况
			$userpoint =  UserPointlog::where("uid",$uid)
								 ->field('id,sum(point) as count , store_id,addtime , curpoint,type_cn ')
								 ->where("type",1)
								 ->page($page,$limt)
								 ->group('store_id')->order('addtime desc')->select();
		}
		foreach ($userpoint as $key => &$value) {
			$value["storname"] =$this->storeid($value["store_id"]);
		}

		return $userpoint;
	}


/*******************************************************************/
	/**
	 * 地址列表
	 */
	public function dresslist($uid){
		$addresslist = UserAddress::all(['uid'=>$uid]);
		return $addresslist;
	}
	
	/**
	 * 门店查询
	 */
	public function storeid($id){
		return Db::table("ys_store")->where("id",$id)->find();
	}
	/**
	 * 用户保存自己的地址
	 */
	public function saveaddress($post){
		$useraddress  	= new UserAddress;
		if(array_key_exists("is_default",$post)){
			$isdefaule = 1;
		}else{
			$isdefaule = 0;
		}
		$useraddress -> uid        = session('_user_uid_')['uid'];
		$useraddress -> consignee  = $post['consignee'];//收货人
		$useraddress -> email      =  $post['email'];
		$useraddress -> country    = $post['country'];
		$useraddress -> province   =  $post['province'];
		$useraddress -> city       =  $post['city'];
		$useraddress -> zipcode    =  $post['zipcode'];
		$useraddress -> area       =  $post['area'];
		$useraddress -> address    =  $post['address'];
		$useraddress -> mobile     =  $post['mobile'];
		$useraddress -> is_default =  $isdefaule;
		$useraddress -> addtime    =  time();
		$useraddress ->save();
		if($isdefaule==1){
			$this->serdefauledress($useraddress ->id,$useraddress->uid);	
		}
		return true;
	}

	/**
	 * 编辑地址
	 */
	public function edtiordress($post){
		$useraddress  	= new UserAddress;

		$result = $useraddress->allowField(true)->where("id", $post['id'])->update($post);
		return $result;
	}
	/**
	 * 获取单条的地址
	 */
	public function getonedress($id){
		return Db::table("ys_user_address")->where("id",$id)->find();
		// return UserAddress::get($id)->toArray();
	}

	/**
	 *删除地址
	 */
	public function deletedress($id){
		$useraddress =UserAddress::get($id);
		$useraddress->delete();
		return 1;
	}

	/**
	 * 设为默认地址
	 */
	public function serdefauledress($id,$uid){
		Db::table("ys_user_address")->where("uid",$uid)->update(['is_default' => 0]);
		Db::table("ys_user_address")->where("id",$id)->update(['is_default' => 1]);
	}
/*******************************************************************/
	/**
	 * 登录
	 */
	public function login($post){
		$user = User::where("mobile",$post['tele'])->get();
		if($user){
			if($user->password ==MD5($post['password'])){
				$data =["mobile"   => $user->mobile,
						"password" => $user->password,
						'openid'   => $user->openid,
						"uid"      => $user->uid,];
				session('_user_uid_',$data);
				return true;
			}
			return false;
		}
		return false;
	}

	/**
	 * 微信自动登录
	 */
	public function loginbyweichart($openid){
		$user = Db::table()->where("openid",$openid)->find();
		if(!empty($user)){
			$data =[ 	"mobile"       	 => $user["mobile"],
					"password"       => $user["password"],
					'openid'   		 => $user["openid"],
					"uid"     		 => $user["uid"],];
			session('_user_uid_',$data);
			return true;
		}
		return false;	
	}

	/**
	 * 退出登录
	 */
	public function loglout(){
		session('_user_uid_',null);
	}
/******************************************************************************/
	/**
	 * 用户余额的增加
	 */
	public function userwalletadd(array $array){
		$use = User::where('uid', $array['uid'])->setInc('user_money', $array['point']);
		$this-> userwalletlog($array);
		return 1;//减少成功
	}

	/**
	 * 消费减少
	 */
	public function userwalletdesc(array $array){
		$use1 = User::where('uid', $array['uid'])->find()->toArray();
		if($use1['user_money']<$array['point']){
			return 3;//月不足就是3
		}
		$use = User::where('uid', $array['uid'])->setInc('total_amount', $array['point']);//消费总额度
		$use = User::where('uid', $array['uid'])->setDec('user_money', $array['point']);
		$this-> userwalletlog($array);
		return 1;//增加成功
	}

	

	/**
	 * 日志类操作
	 */
	public function userwalletlog(array $array){
		$userwalletlog  =  new UserWalletLog;
		$userwalletlog ->uid 		= $array['uid'];
		$userwalletlog ->uname 		= $array['uname'];
		$userwalletlog ->chargetype = $array['chargetype'];
		$userwalletlog ->charge_cn  = $array['charge_cn'];
		$userwalletlog ->addtime 	= time();
		$userwalletlog ->save();
	}

	
/*********************************************/
	 
	 /**
	  * 插入用户优惠券
	  * @param  [type] $array [description]
	  * @return [type]        [description]
	  */
	 public function userycardadd($array){

	 	$userycard  = new UserYcard;
	 	$result = DbShowcollo::add($userycard,$array);
	 	return $result;
	 }

	 /**
	  * 获取用户优惠券
	  * @return [type] [description]
	  */
	 public function getycard($uid){
	 	$userycard  = new UserYcard;
	 	$res = UserYcard::where('uid',$uid)->select();
	 	$pres = [];
	 	foreach ($res as $key => $value) {
	 		$val = $value->toArray();
	 		if(time() > $val['use_time']){
	 			$val['isuse']= 0;
	 		}else{
	 			$val['isuse']= 1;
	 		}	
	 		$val['ycard'] = $this->getyouhuibyid($val['coupon_id']);
	 		array_push($pres, $val);
	 	}
	 	return $pres;
	 }

	 /**
	  * 用优惠券id获取优惠券的东西
	  * @param  [type] $id [description]
	  * @return [type]     [description]
	  */
	 public function getyouhuibyid($id){
	 	$res =  \app\comm\model\Coupon::get($id)->toArray();
	 	return $res;
	 }

	 /**
	  * 检查用户获取优惠券的条件
	  * @return [type] [description]
	  */
	 public function checkuidycard($id,$uid){
	 	$map['uid']=$uid;
	 	$map['coupon_id']=$id;//dd($map);
	 	$lsit = UserYcard::where("1=1")->where($map)->select();
	 	if($lsit){
	 		return 1;
	 	}
	 	return 0;
	 }
/*******************用户收藏***********************/
	/**
	 * 用户收藏商品
	 * @return [type] [description]
	 */
	public function usercollectgoods($array){
		$usercollect = new UserCollect;
		$map['uid'] =$array['uid'];
		$map['goods_id'] =$array['goods_id'];
		$map['store_id'] =$array['store_id'];
		$check = $this->check_goods_uid($map);
		if(!$check){
			UserCollect::destroy($map);
			return 5;
		}
		$result = DbShowcollo::add($usercollect,$array);
		return $result;
	}

	/**
	 * 我的收藏
	 */
	public function getcolecgo($uid){
		$usercollect = new UserCollect;
		$goodservic = new GoodsService;
		$reslist = DbShowcollo::getselbysigfield($usercollect,'uid',$uid);
		foreach ($reslist as $key => &$value) {
			$value['goods']=$goodservic->getgoodbyid($value['goods_id']);
		}
		return $reslist ;
	}

	/**
	 * 商品收藏检查唯一性
	 */
	public function check_goods_uid($map){
		$cle = UserCollect::where($map)->select();
		if($cle){
			return 0;
		}
		return 1;
	}

	/**
	 * 获取用户信息，
	 */
	public function getUserInfo($uid){
		$useri  =  Db::table("ys_user")->where("uid",$uid)->find();
		if($useri["sex"]==0){
				$useri["sex_cn"] ="保密";
		}
		if($useri["sex"]==1){
			$useri["sex_cn"] ="男";
		}
		if($useri["sex"]==2){
			$useri["sex_cn"] ="女";
		}
		//var_dump($useri);
		return $useri;
	}

	/**
	 * 从缓存中获取用户信息
	 */
	public function getUserInfoByCash($uid){
		$userinfo = Cache::get("userinfo__".$uid);
		if(empty($userinfo)){
			$userinfo = $this->getUserInfo($uid);
			Cache::set("userinfo__".$uid,$userinfo,3600);
			return $userinfo;
		}
		return $userinfo;
	}

	/**
	 * 清除用户缓存
	 */
	public function clearUserCash($uid){
	   Cache::rm("userinfo__".$uid); 
	}
	
}

